/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.

 * Author: newma
 * Date: 7/1/15
 * Descript:

 *  Modified:
 */

var mysql = require('mysql');

var pool = mysql.createPool({
    connectionLimit : 10,
    host            : '61.145.116.206',
    user            : 'xysq',
    password        : 'lemon',
    port            : 22226,
    database        : 'xysq',

    //自定义
    queryFormat     : function (query, values) {
                        if (!values) {
                            return query;
                        }
                        return query.replace(/\:(\w+)/g, function (txt, key) {
                                                                if (values.hasOwnProperty(key)) {
                                                                    console.log('replace word [:' + key + '] with ['+ this.escape(values[key]) + ']')
                                                                    return this.escape(values[key]);
                                                                }
                                                                return txt;
                                                          }.bind(this));
                        }
});

module.exports = {
    /**
     * 获得数据库连接
     * @param cb： function(err, connection)
     */
    connect: function(cb) {
        pool.getConnection(cb);
    },

    /**
     * 执行单条数据SQL语句
     * @param sql
     * @param obj
     * @param cb
     */
    query: function(sql, obj, cb) {
        pool.getConnection(function(err, conn) {
            if (err) {
                cb(err);
                return;
            }

            conn.query(sql, obj, function(err, results) {
                cb(err, results);
                conn.release();
            });
        })
    },

    /**
     * 释放获得的数据库连接
     * @param conn
     */
    release: function(conn) {
        conn.release();
    },

    /**
     * 关闭数据访问模块
     * @param cb: function(err)
     */
    destory: function(cb) {
        pool.end(cb);
    }
};
